<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/1/9
 * Time: 下午3:39
 */

namespace Biz\model\activity;

use Biz\model\activity\FullShippingPlan as mFullShippingPlan;
use Biz\model\activity\FullShippingGoods as mFullShippingGoods;
use Doraemon\pockets\datebase\BaseDbModel;

class FullShipping extends BaseDbModel
{
    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_activity';

    const _DATABASE_ = 'shop_activity';

    const _TABLE_NAME = 'full_shipping';

    //状态
    const STATUS_ACTIVE = 1;//正常
    const STATUS_INVALID = 0; // 失效
    const STATUS_DELETE = 9;//删除状态


    const TYPE_TOTAL_AMOUNT = 1;//满X元包邮
    const TYPE_TOTAL_PIECES = 2;//满X件包邮

    public static $typeDesc = [
        self::TYPE_TOTAL_AMOUNT => '满X元包邮',
        self::TYPE_TOTAL_PIECES => '满X件包邮'
    ];

    public static function getActivePlanList($shopIds, $status = self::STATUS_ACTIVE, $withTitle = false, $is_curr = false, $is_has_end = false)
    {

        $now_date = date("Y-m-d H:i:s");
        $data = [];
        $map = [
            'shop_id' => $shopIds,
        ];
        if (!is_null($status)) {
            $map['status'] = $status;
        }
        if ($is_has_end) {
            unset ($map['end_time[>]']);
        }

        if ($is_curr) {
            $map = array_merge($map, [
                'start_time[<]' => $now_date,
            ]);
        }

        $list = self::select('*', [
            'AND' => $map,
            'ORDER' => ['status' => 'DESC', 'start_time' => 'DESC'],
        ]);
        if (empty($list)) {
            return $data;
        }

        $shipping_ids = array_column($list, 'id');

        $planList = mFullShippingPlan::getActiveList($shipping_ids, $status, ['shipping_id' => $shipping_ids]);
        $where = ['shipping_id' => $shipping_ids];
        if (!is_null($status)) {
            $where['status'] = $status;
        }
        $shippingGoods = mFullShippingGoods::getList($where, ['shipping_id', 'goods_id']);
        $goodsList = [];
        foreach ($shippingGoods as $row) {
            $goodsList[$row['shipping_id']][] = $row['goods_id'];
        }
        if ($withTitle) {
            $list = array_column($list, null, 'id');

            foreach ($planList as $shop_id => $plans) {
                $planList[$shop_id] = array_map(function ($plan) use ($list, $goodsList) {
                    $goodsIds = [];
                    if (isset($goodsList[$plan['shipping_id']]) && $goodsList[$plan['shipping_id']]) {
                        $goodsIds = $goodsList[$plan['shipping_id']];
                    }
                    $plan['type'] = $list[$plan['shipping_id']]['type'];
                    $plan['title'] = $list[$plan['shipping_id']]['title'];
                    $plan['start_time'] = $list[$plan['shipping_id']]['start_time'];
                    $plan['end_time'] = $list[$plan['shipping_id']]['end_time'];
                    $plan['all_goods'] = $list[$plan['shipping_id']]['all_goods'];
                    $plan['goods_ids'] = $goodsIds;
                    $plan['status'] = $list[$plan['shipping_id']]['status'];
                    return $plan;
                }, $plans);
            }

        }
        return $planList;

    }

    public static function getCurrInfos($shop_id)
    {
        $now_date = date("Y-m-d");
        $fullInfos = self::select("*", [
            "shop_id" => $shop_id,
            "start_time[<]" => $now_date,
            "end_time[>]" => $now_date,
            'status' => self::STATUS_ACTIVE
        ]);

        if (!$fullInfos) {
            return [];
        }

        $shippingIds = array_column($fullInfos, 'id');
        $planInfos = FullShippingPlan::getInfos($shippingIds);

        return array_map(function ($fullInfo) use ($planInfos) {
            $fullInfo['planinfos'] = $planInfos[$fullInfo['id']];

            return $fullInfo;
        }, $fullInfos);

    }

    public static function addData($shop_id, $fields)
    {
        $ret = self::insert([
            'shop_id' => $shop_id,
            'title' => $fields['title'],
            'type' => $fields['type'],
            'start_time' => $fields['start_time'],
            'end_time' => $fields['end_time'],
            'all_goods' => $fields['all_goods'],
            'status' => self::STATUS_ACTIVE
        ]);
        if ($ret->errorCode() !== '00000') {
            return false;
        }
        return self::id();

    }

    /**
     * 判断时间段是否重叠
     * @param $shop_id
     * @param $start_time
     * @param $end_time
     * @param bool $is_update
     * @param int $id
     * @return bool
     * @throws \Exception
     */
    public static function TimeRangeIsCover($shop_id, $start_time, $end_time, $is_update = false, $id = 0)
    {
        $map = [];
        $map['shop_id'] = $shop_id;
        if ($is_update && $id) {
            $map['id[!]'] = $id;
        }
        $map['OR'] = [
            'AND #1' => [
                'start_time[<=]' => $start_time,
                'end_time[>]' => $start_time,
            ],
            'AND #2' => [
                'start_time[<]' => $end_time,
                'end_time[>=]' => $end_time,
            ],
            'AND #3' => [
                'start_time[<=]' => $start_time,
                'end_time[>=]' => $end_time,
            ],
        ];
        $map['status'] = self::STATUS_ACTIVE;

        $isExist = self::get('*', $map);
        return $isExist;
    }

    public static function edit($id, $shop_id, array $data)
    {
        $data['edittime'] = date('Y-m-d H:i:s');
        $ret = self::update($data, [
            'id' => $id,
            'shop_id' => $shop_id,
        ]);
        if ($ret->errorCode() !== '00000') {
            return false;
        }
        return true;
    }


    /**
     * 获取商铺最近的活动信息  正在进行中 或  还未开始
     * @param $shopIds
     * @return array
     */
    public static function getRecentlyShipping($shopIds)
    {
        $currTime = date('Y-m-d H:i:s');
        $datas = self::select('*', [
            'shop_id' => $shopIds,
            'end_time[>]' => $currTime,
            'status' => self::STATUS_ACTIVE,
            'ORDER' => ['end_time' => 'ASC']
        ]);
        $Rst = [];
        foreach ($datas as $data) {
            if (!isset($Rst[$data['shop_id']])) {
                $Rst[$data['shop_id']] = $data;
            }
        }
        $shippingIds = array_column($Rst, 'id');
        $shippingPlans = mFullShippingPlan::getInfos($shippingIds);
        $shippingGoods = mFullShippingGoods::getList([
            'shipping_id' => $shippingIds,
            'status' => mFullShippingGoods::STATUS_ACTIVE,
        ], ['shipping_id', 'goods_id']);
        $goodsList = [];
        foreach ($shippingGoods as $row) {
            $goodsList[$row['shipping_id']][] = $row['goods_id'];
        }
        foreach ($Rst as $shop_id => $item) {
            $Rst[$shop_id]['is_happening'] = $item['start_time'] < $currTime ? 1 : 0;
            $Rst[$shop_id]['expire'] = self::CacheExpire($item['start_time'], $item['end_time']);
            $Rst[$shop_id]['planinfo'] = $shippingPlans[$item['id']];
            $Rst[$shop_id]['all_goods'] = $item['all_goods'];
            $Rst[$shop_id]['goods_ids'] = isset($goodsList[$item['id']]) ? $goodsList[$item['id']] : [];
        }


        return $Rst;
    }

    private static function CacheExpire($start_time, $end_time)
    {
        $currentTime = time();
        $start_time = strtotime($start_time);
        $end_time = strtotime($end_time);
        $expire = 0;
        if ($currentTime < $start_time) {
            $expire = $start_time - $currentTime;
        } else if ($start_time < $currentTime && $end_time > $currentTime) {
            $expire = $end_time - $currentTime;
        }
        return $expire;
    }

    public static function getInfoById($id)
    {
        $now = date("Y-m-d");
        $info = self::get("*", [
            "id" => $id,
            "end_time[>]" => $now,
            'status' => self::STATUS_ACTIVE
        ]);
        return $info;
    }

    public static function getList($where)
    {
        $result = [
            'list' => [],
            'total' => 0
        ];

        $list = self::select('*', [
            'AND' => $where['AND'],
            'LIMIT' => $where['LIMIT'],
            'ORDER' => $where['ORDER']
        ]);
        if (empty($list)) {
            return $result;
        }

        $shippingIds = array_column($list, 'id');
        $planInfo = mFullShippingPlan::getInfos($shippingIds);

        $list = array_column($list, null, 'id');
        $data = [];
        foreach ($list as $row) {
            $unitStr = ($row['type'] == self::TYPE_TOTAL_PIECES) ? '件' : '元';
            $data[$row['id']] = $row;
            $data[$row['id']]['fullship_id'] = $row['id'];
            $planList = '';
            foreach ($planInfo as $shippingId => $info) {
                foreach ($info as $item) {
                    if($shippingId == $row['id']) {
                        $planList .= '满' . $item['total_unit'] . $unitStr . '包邮' . $item['province_desc']. "\n";
                        $data[$shippingId]['plans'] = $planList;
                    }
                }
            }
        }

        return $data ? ['list' => array_values($data), 'total' => self::getCount($where['AND'])] : $result;
    }

    public static function getCount($where)
    {
        return self::count('*', $where);
    }

}